package com.shengqi.xinnongren.work.ui.home.activities;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.config.user.UserManager;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.work.model.HttpRespond;
import com.shengqi.xinnongren.work.ui.home.adapter.ChooseAreaAdapter;
import com.shengqi.xinnongren.work.ui.home.adapter.ChooseStoreAdapter;
import com.shengqi.xinnongren.work.ui.home.model.StoreListBean;
import com.shengqi.xinnongren.work.ui.home.presenter.ChooseStorePresenter;
import com.shengqi.xinnongren.work.ui.home.view.ChooseStoreView;
import com.yanzhenjie.permission.AndPermission;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class ChooseStoreActivity extends BaseMvpActivity<ChooseStoreView, ChooseStorePresenter> implements ChooseStoreView, AMapLocationListener, AMap.InfoWindowAdapter {


    @BindView(R.id.rv_area)
    RecyclerView mRvArea;
    @BindView(R.id.rv_store)
    RecyclerView mRvStore;
    @BindView(R.id.map)
    MapView mMapView;
    @BindView(R.id.tv_cur_store)
    TextView mTvCurStore;

    AMap aMap;

    private String longitude, latitude;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;


    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_choose_store;
    }

    MyLocationStyle myLocationStyle;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);

        AndPermission.with(this).permission(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(permissions -> initMap()).start();
    }

    private void initMap() {
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));


        myLocationStyle = new MyLocationStyle();

        //初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//只定位一次。

        //--------------------定位点设置---------------
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher));
        myLocationStyle.strokeColor(Color.TRANSPARENT);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.TRANSPARENT);// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(0.1f);// 设置圆形的边框粗细

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);


        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位回调监听
        mLocationClient.setLocationListener(this);

        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mLocationClient.startLocation();
        aMap.setInfoWindowAdapter(this);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
//                mTvCurAddress.setText(aMapLocation.getCity());
                longitude = aMapLocation.getLongitude() + "";
                latitude = aMapLocation.getLatitude() + "";

                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                mLocationClient.stopLocation();
                getData(longitude, latitude);

            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
        mLocationClient.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    private ChooseAreaAdapter mAreaAdapter;
    private List<StoreListBean> mAreaList;

    private ChooseStoreAdapter mStoreAdapter;
    private List<StoreListBean.StoreChildListBean> mStoreList;

    @Override
    protected void initView() {

        mTvCurStore.setText(UserManager.getInstance().getStoreName());

        mAreaList = new ArrayList<>();
        mAreaAdapter = new ChooseAreaAdapter(this, mAreaList);
        mRvArea.setLayoutManager(new LinearLayoutManager(this));
        mRvArea.setAdapter(mAreaAdapter);
        mAreaAdapter.setOnItemClickListener(position -> {
            mStoreList.clear();
            List<StoreListBean.StoreChildListBean> beanList = mAreaList.get(position).getStoreList();
            mStoreList.addAll(beanList);
            boolean isSelected = false;
            for (int i = 0; i < beanList.size(); i++) {
                if (beanList.get(i).getCurr() == 1) {
                    mStoreAdapter.setCurChosePosition(i);
                    isSelected = true;
                    break;
                }
            }

            if (!isSelected) {
                mStoreAdapter.setCurChosePosition(0);
            }

            mStoreAdapter.notifyDataSetChanged();
            //地图移动并显示marker

            showMarker(mAreaList.get(position).getStoreList());
        });

        mStoreList = new ArrayList<>();
        mStoreAdapter = new ChooseStoreAdapter(this, mStoreList);
        mRvStore.setLayoutManager(new LinearLayoutManager(this));
        mRvStore.setAdapter(mStoreAdapter);
        mStoreAdapter.setOnItemClickListener(new ChooseStoreAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //地图移动并显示marker
                StoreListBean.StoreChildListBean bean = mStoreList.get(position);
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(bean.getY(), bean.getX())));
                aMap.addMarker(new MarkerOptions().position(new LatLng(bean.getY(), bean.getX())).icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_location))
                        .title(bean.getName() + "#" + bean.getId())
                        .snippet(bean.getAddress())).showInfoWindow();
//                aMap.getMapScreenMarkers();

            }

            @Override
            public void onItemChoiceClick(int position) {
                saveStore(mStoreList.get(position));
            }
        });

    }

    private void saveStore(StoreListBean.StoreChildListBean storeChildListBean) {
        if (UserManager.getInstance().isLogin()) {
            //保存服务器
            mPresenter.saveStore(storeChildListBean.getId(), storeChildListBean.getName());
        } else {
            UserManager.getInstance().saveStoreId(storeChildListBean.getId());
            UserManager.getInstance().saveStoreName(storeChildListBean.getName());
            mTvCurStore.setText(storeChildListBean.getName());
            gotoMain();
        }

    }

    private void gotoMain() {
        closeAllActivities();
        startActivity(new Intent(this, MainActivity.class));
    }

    private void showMarker(List<StoreListBean.StoreChildListBean> storeList) {
        aMap.clear();
        ArrayList<MarkerOptions> markerOptions = new ArrayList<>();

        for (StoreListBean.StoreChildListBean bean : storeList) {
            MarkerOptions options = new MarkerOptions();
            options.position(new LatLng(bean.getY(), bean.getX()))
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_location))
                    .title(bean.getName() + "#" + bean.getId())
                    .snippet(bean.getAddress());

            markerOptions.add(options);
        }

        aMap.addMarkers(markerOptions, true);

        aMap.setOnMarkerClickListener(marker -> {
            if (!marker.isInfoWindowShown()) {
                marker.showInfoWindow();
            }
            return false;
        });

        aMap.setOnInfoWindowClickListener(marker ->
                StoreDetailsActivity.start(this, marker.getTitle().split("#")[1], latitude, longitude)
        );
    }

    /**
     * 自定义InfoWindow 样式 回调
     *
     * @param marker
     * @return
     */
    @Override
    public View getInfoWindow(Marker marker) {

        View infoWindow = LayoutInflater.from(this).inflate(
                R.layout.custom_info_window, null);
        TextView tvName = infoWindow.findViewById(R.id.info_window_name);
        TextView tvAddress = infoWindow.findViewById(R.id.info_window_address);
        tvName.setText(marker.getTitle().split("#")[0]);
        tvAddress.setText(marker.getSnippet());
        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected ChooseStorePresenter createPresenter() {
        return new ChooseStorePresenter();
    }

    private void getData(String longitude, String latitude) {
        mPresenter.getStoreList(longitude, latitude);
    }

    @Override
    public void showStoreList(HttpRespond<List<StoreListBean>> respond) {
        if (respond.result == 1) {
            List<StoreListBean> data = respond.data;
            mAreaList.clear();
            mAreaList.addAll(data);

            boolean isSelected = false;

            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getCurr() == 1) {
                    mAreaAdapter.setCurChosePosition(i);
                    isSelected = true;
                    break;
                }

            }
            if (!isSelected) {
                mAreaAdapter.setCurChosePosition(0);
            }

            mAreaAdapter.notifyDataSetChanged();


        } else
            ToastHelper.getInstance(this).showWarn(respond.message);
    }

    @Override
    public void showSaveStoreRes(HttpRespond respond) {
        if (respond.result == 1) {
            UserManager.getInstance().saveStoreId(mPresenter.getStoreId());
            UserManager.getInstance().saveStoreName(mPresenter.getStoreName());
            mTvCurStore.setText(mPresenter.getStoreName());
            gotoMain();
        }

        ToastHelper.getInstance(this).showWarn(respond.message);
    }

    @Override
    public void showLoadingView() {

    }

    @Override
    public void hideLoadingView() {

    }

    @Override
    public void onNetworkError() {

    }


}
